package com.springcloud.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.springcloud.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: 顾志杰
 */
@Slf4j
@Service
public class JwtService {

    private static final String KEY = "changIT";

    private static final String ISSUER = "gu";

    private static final String USERNAME = "username";

    /* 过期时间 */
    private static final Long TOKEN_EXP_TIME = 60000L;

    /**
     * 生成token
     * @param account
     * @return
     */
    public String token(Account account) {
        Date now = new Date();

        /* 声明一个算法 生成token */
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXP_TIME))
                .withClaim(USERNAME,account.getUsername())
                .sign(algorithm);
        log.info("jwt generated user = {}",account.getUsername());
        return token;
    }


    /**
     * 校验token
     * @param token
     * @param username
     * @return
     */
    public boolean verfiy(String token,String username) {
        log.info("verfiying jwt - user = {}",username);
        try {
            /* 声明一个算法 验证解密 */
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .withClaim(USERNAME,username)
                    .build();
            verifier.verify(token);
            return true;
        }catch (Exception e){
            log.info("auth failed ",e);
            return false;
        }

    }
}
